<?php
session_start();
header('Content-Type: text/html; charset=utf-8');

// 在后端获取前端表单数据的方法是使用全局数组 $_GET  $_POST
$userName = trim($_POST['userName']);
$pwd = trim($_POST['pwd']);

// 进行必要的验证
if (!strlen($userName) || !strlen($pwd)) {
    echo "<script>alert('用户名或密码没有填写');history.back();</script>";
    exit;
} elseif (!preg_match('/^[a-zA-Z0-9]{3,10}$/', $userName)) {
    echo "<script>alert('用户名必填，且只能由大小写字符和数字组成，长度在3到10个字符!');history.back();</script>";
    exit;
} elseif (!preg_match('/^[a-zA-Z0-9_*]{6,10}$/', $pwd)) {
    echo "<script>alert('密码必填,且只能大小写和数字,以及*_构成,长度为6到10个字符!');history.back();</script>";
    exit;
}

include_once "conn.php";
// 判断用户名是否存在
$sql = "select * from user where userName='$userName' and pwd='" . md5($pwd) . "'";
$result = mysqli_query($conn, $sql);
if (!mysqli_num_rows($result)) {
    echo "<script>alert('该用户不存在');location.replace(document.referrer);</script>";
    unset($_SESSION['loggedUserName']);
    unset($_SESSION['isAdmin']);
    exit;
} else {
    $_SESSION['loggedUserName'] = $userName;
    // 判断是否是管理员
    $info = mysqli_fetch_array($result);
    $_SESSION['isAdmin'] = $info['admin'];

    echo "<script>alert('用户" . $_SESSION['loggedUserName'] . "登录成功');location.href='index.php'</script>";
}




